<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getImportJsData } from '@/utils/excel'
import { batchAddEmplApi } from '@/api/employee'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 判断文件大小
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) return true

      this.$message.warning('请勿上传超过1m大小的文件')

      return false
    },
    // 选择文件，并发送请求
    async handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 中英文对应关系
      const headerRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      // 处理表格数据
      const result = getImportJsData(results, headerRelation)
      // 发送请求和后续逻辑处理
      await batchAddEmplApi(result)
      this.$message.success('添加成功')
      this.$router.back()
    }
  }
}
</script>
